package BandB.Tool.GPhoneManager.AppManager.AppResore;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import BandB.Tool.GPhoneManager.R;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class BackupListAdapter extends ArrayAdapter<BackupItem> {
	private static final String TAG = BackupListAdapter.class.getSimpleName();
	private static final String UNKNOWN = "Unkown";
	private LayoutInflater mInflater;
	private PackageManager mPackageManager;
	private LinkedList<BackupItem> mBackupItemsList;
	private HashMap<BackupItem, Drawable> mIconCache;
	private HashMap<BackupItem, String> mSizeCache;
	private HashMap<BackupItem, String> mDateCache;
	private HashMap<BackupItem, String> mVersionCache;
//	private Context mContext;

	public BackupListAdapter(Context context) {
		super(context, 0);
//		mContext = context;
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mPackageManager = context.getPackageManager();
		mBackupItemsList = new LinkedList<BackupItem>();

		mIconCache = new HashMap<BackupItem, Drawable>();
		mSizeCache = new HashMap<BackupItem, String>();
		mDateCache = new HashMap<BackupItem, String>();
		mVersionCache = new HashMap<BackupItem, String>();
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mBackupItemsList.size();
	}

	public BackupItem getInfo(int position) {
		return mBackupItemsList.get(position);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.backup_list_item, parent,
					false);
		}
		ImageView appIcon = (ImageView) convertView
				.findViewById(R.id.imgViewBackUpList);
		TextView appNameTextView = (TextView) convertView
				.findViewById(R.id.app_name);
		TextView appVersionTextView = (TextView) convertView
				.findViewById(R.id.app_version);
		TextView backupSizeTextView = (TextView) convertView
				.findViewById(R.id.apk_size);
		TextView backupDateTextView = (TextView) convertView
				.findViewById(R.id.backup_date);
		CheckBox recoverCheckbox = (CheckBox) convertView
				.findViewById(R.id.recover_checkbox);
		BackupItem item = getInfo(position);
		PackageInfo packageInfo = item.getPackageInfo();

		appIcon.setImageDrawable(mIconCache.get(item));
		appNameTextView.setText(packageInfo.applicationInfo.loadLabel(
				mPackageManager).toString());
		appVersionTextView.setText(formatVersion(packageInfo.versionName));
		backupSizeTextView.setText(mSizeCache.get(item));
		backupDateTextView.setText(mDateCache.get(item));
		recoverCheckbox.setChecked(item.isChecked());
		return convertView;
	}

	public void addFileInfo(BackupItem item) {
		if (null != item) {
			try {
				Drawable icon = item.getPackageInfo().applicationInfo
						.loadIcon(mPackageManager);

				mIconCache.put(item, icon);
				mVersionCache.put(item, item.getPackageInfo().versionName);
				File file = item.getBackupFile();
				mDateCache.put(item, formatDate(file));
				mSizeCache.put(item, formatSize(file));
				mBackupItemsList.add(item);
			} catch (Exception e) {
				if (mBackupItemsList.contains(item)) {
					mBackupItemsList.remove(item);
				}
				Log.e(TAG, "broken apk file.");
			}

		}
	}

	public void checkAll() {
		int size = getCount();
		for (int i = 0; i < size; i++) {
			getInfo(i).setChecked(true);
		}
		notifyDataSetChanged();
	}

	public void checkNothing() {
		int size = getCount();
		for (int i = 0; i < size; i++) {
			getInfo(i).setChecked(false);
		}
		notifyDataSetChanged();
	}

	public List<BackupItem> getCheckedItem() {
		List<BackupItem> checkList = new ArrayList<BackupItem>();
		int size = getCount();
		for (int i = 0; i < size; i++) {
			BackupItem item = getInfo(i);
			if (item.isChecked()) {
				checkList.add(item);
			}
		}
		return checkList;
	}

	/**
	 * Delete all the file items in this adapter.
	 */
	public void deleteAllFiles() {
		mBackupItemsList.clear();
		mIconCache.clear();
		mDateCache.clear();
		mSizeCache.clear();
		mVersionCache.clear();
	}

	public void deleteFile(List<BackupItem> backupFileList) {
		int size = backupFileList.size();
		for (int i = 0; i < size; i++) {
			BackupItem item = backupFileList.get(i);
			if (mBackupItemsList.contains(item)) {
				mBackupItemsList.remove(item);
				mIconCache.remove(item);
				mDateCache.remove(item);
				mSizeCache.remove(item);
				mVersionCache.remove(item);
			}
			File oneFile = item.getBackupFile();
			if (oneFile.exists()) {
				if (oneFile.delete()) {
					Log.i(TAG, oneFile.getName() + "delete successfully!");
				} else {
					Log.e(TAG, oneFile.getName() + "delete failed!");
				}
			}
		}
	}

	private String formatVersion(String versionName) {
		String formatedVersion = "";

		if (!TextUtils.isEmpty(versionName)) {
			formatedVersion = "Version " + versionName;
		}
		return formatedVersion;
	}

	private String formatSize(File file) {
		if (null != file) {
			long size = file.length();
			String sizeString = String.valueOf(size >> 10);
			return sizeString + "KB";
		} else {
			return UNKNOWN;
		}
	}

	private String formatDate(File file) {
		if (null != file) {
			long longDate = file.lastModified();
			Date date = new Date(longDate);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.format(date);
		} else {
			return UNKNOWN;
		}
	}

	public void setCheckedAt(int position) {
		getInfo(position).setChecked(!getInfo(position).isChecked());
		notifyDataSetChanged();
	}

}
